﻿
using Microsoft.Extensions.DependencyInjection;

namespace LJ.Host.Abstractions.DependencyInjection;

public class DependencyInjectionFactory(IServiceScopeFactory serviceScopeFactory, IHybridProvider<IServiceProvider> serviceProviderHybridProvider) : IDependencyInjectionFactory
{
    private readonly IServiceScopeFactory _serviceScopeFactory = serviceScopeFactory;
    private readonly IHybridProvider<IServiceProvider> _serviceProviderHybridProvider = serviceProviderHybridProvider;

    public IServiceScope CreateScope()
    {
        var serviceProvider = _serviceProviderHybridProvider.Value;
        if (serviceProvider == null)
        {
            return _serviceScopeFactory.CreateScope();
        }

        return new NonDisposedHttpContextServiceScope(serviceProvider);
    }

    protected class NonDisposedHttpContextServiceScope(IServiceProvider serviceProvider) : IServiceScope
    {

       
        public IServiceProvider ServiceProvider { get; } = serviceProvider;

        /// <summary>因为是HttpContext的，啥也不做，避免在using使用时被释放</summary>
        public void Dispose()
        { }
    }
}
